package com.baocai.tools.controller;

import com.baocai.tools.domain.JsonData;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.*;

/**
 * @author ：minyang
 * @date ：Created in 2019/7/17 15:40
 * 文件上传
 */
@RestController
public class FileController {

    //    private static final String filePath = "/Users/jack/Desktop/person/springboot/xdclass_springboot/src/main/resources/static/images/";
    @Value("${web.upload-path}")
    private String filePath;


    @RequestMapping(value = "upload")
    public JsonData upload(@RequestParam("head_img") MultipartFile file, HttpServletRequest request) {

        //file.isEmpty(); 判断图片是否为空
        //file.getSize(); 图片大小进行判断

        String name = request.getParameter("name");
        System.out.println("用户名：" + name);

        // 获取文件名
        String fileName = file.getOriginalFilename();
        System.out.println("上传的文件名为：" + fileName);

        // 获取文件的后缀名,比如图片的jpeg,png
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        System.out.println("上传的后缀名为：" + suffixName);

        // 文件上传后的路径
        fileName = UUID.randomUUID() + suffixName;
        System.out.println("转换后的名称:" + fileName);

        File dest = new File(filePath + fileName);

        try {
            file.transferTo(dest);

            return new JsonData(0, fileName);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new JsonData(-1, "fail to save ", null);
    }

//    @PostMapping("/multiple")
//    public JsonData multiple(@RequestParam MultipartFile[] files, @RequestParam(value = "subPath", defaultValue = "") String subPath, HttpServletRequest request) throws Exception {
//        Map map = new HashMap();
//        String url = "";
//        List<String> successStr = new ArrayList<>();
//
//        String outPath = this.preReadUploadUtil.getOutPrefix();
//        String realPath = this.preReadUploadUtil.getUploadPath();
//        if (!StringUtils.isEmpty(subPath)) {
//            realPath = realPath + subPath + "/";
//            outPath = outPath + subPath + "/";
//        }
//
//        RandomAccessFile raFile = null;
//        BufferedInputStream inputStream = null;
//        try {
//            for (int i = 0; i < files.length; i++) {
//                String originalFilename = files[i].getOriginalFilename();
//                //判断文件夹是否存在
//                File file1 = new File(realPath);
//                if (!file1.exists() && !file1.isDirectory()) {
//                    file1.mkdirs();
//                }
//                String uploadFileName = System.currentTimeMillis() + "_" + originalFilename;
//
//                File dirFile = new File(realPath, uploadFileName);
//                //以读写的方式打开目标文件
//                raFile = new RandomAccessFile(dirFile, "rw");
//                raFile.seek(raFile.length());
//                inputStream = new BufferedInputStream(files[i].getInputStream());
//                byte[] buf = new byte[1024];
//                int length = 0;
//                while ((length = inputStream.read(buf)) != -1) {
//                    raFile.write(buf, 0, length);
//                }
//                url += outPath + uploadFileName + ",";
//                successStr.add(originalFilename);
//                //return super.success("上传成功", savePath + uploadFileName)
//            }
//            url = url.substring(0, url.length() - 1);
//            map.put("url", url);
//            map.put("successStr", successStr);
//            return new JsonData(0, fileName);
//        } catch (Exception e) {
//            map.put("url", url);
//            map.put("successStr", successStr);
//            return new JsonResult(ResultCode.FAIL, "部分上传成功", map);
//        } finally {
//            try {
//                if (inputStream != null) {
//                    inputStream.close();
//                }
//                if (raFile != null) {
//                    raFile.close();
//                }
//            } catch (Exception e) {
//                return super.error("上传失败");
//            }
//        }
//    }
}
